// CSV文件上传相关代码
document.addEventListener('DOMContentLoaded', function() {
    const csvFile = document.getElementById('csvFile');
    const uploadCsvBtn = document.getElementById('uploadCsvBtn');
    const selectedFileName = document.getElementById('selectedFileName');
    const uploadStatus = document.getElementById('uploadStatus');

    if (csvFile) {
        csvFile.addEventListener('change', function(e) {
            const fileName = e.target.files[0]?.name || '';
            selectedFileName.textContent = fileName;
        });
    }

    if (uploadCsvBtn) {
        uploadCsvBtn.addEventListener('click', async function() {
            if (!csvFile.files.length) {
                uploadStatus.innerHTML = '<span class="text-red-500">请先选择文件</span>';
                return;
            }

            const formData = new FormData();
            formData.append('file', csvFile.files[0]);

            try {
                uploadStatus.innerHTML = '<span class="text-blue-500">正在上传...</span>';
                
                const response = await fetch('/api/upload-users', {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();

                if (response.ok) {
                    uploadStatus.innerHTML = `<span class="text-green-500">${result.message}</span>`;
                    if (result.errors && result.errors.length > 0) {
                        uploadStatus.innerHTML += '<div class="mt-2"><strong>错误详情：</strong><ul class="list-disc pl-5">' +
                            result.errors.map(err => `<li class="text-red-500">${err}</li>`).join('') +
                            '</ul></div>';
                    }
                    // 刷新用户列表
                    if (typeof loadUsers === 'function') {
                        loadUsers();
                    }
                } else {
                    uploadStatus.innerHTML = `<span class="text-red-500">上传失败: ${result.error}</span>`;
                }
            } catch (error) {
                uploadStatus.innerHTML = '<span class="text-red-500">上传过程中发生错误</span>';
                console.error('Upload error:', error);
            }

            // 清除文件选择
            csvFile.value = '';
            selectedFileName.textContent = '';
        });
    }
});
